<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9
 * Time: 10:02
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\read\User;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\UserPower;
use Services\Order;
use Services\UserService as UserService;

class OrderController extends ControllerBase
{


    public function orderTabAction(){
        $this->view->pick('order/orderTab');
    }



    /**
     * 百分网课程订单列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180509
     */
    public function courseOrderListAction(){
        Assets::easyUI();
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::viewer();
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/order/courseOrderList.js');
        $this->view->pick('order/courseOrderList');
        Template::exists('Order_CourseList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if ( UserPower::checkUserPower('Order_100Fen_Check')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_checkMenu', 'text' => '订单审核', 'class' => 'bt_list_menu');
        }
        if (UserPower::checkUserPower('Order_100Fen_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_cancel', 'text' => '取消订单', 'icon' => 'fa-trash');
        }

        $temp = Order::$fields;
        $orderState = $temp['orderState'];
        $proofState = $temp['proofState'];
        $orderState[''] = '订单状态';
        $proofState[''] = '审核状态';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_orderState', 'data' => $orderState, 'default' => '','style' => 'width:100px;' );
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_proofState', 'data' => $proofState, 'default' => '','style' => 'width:100px;' );
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Order_CourseList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 平板订单列表
     *
     * @return \Phalcon\Mvc\View
     * create by xjq 20180509
     */
    public function tabOrderListAction(){
        Assets::easyUI();
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::viewer();
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/order/tabOrderList.js');
        $this->view->pick('order/tabOrderList');
        Template::exists('Order_TabletList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();

        if (UserPower::checkUserPower('Order_100Fen_Check')) { //审核凭证
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_checkMenu', 'text' => '订单审核', 'class' => 'bt_list_menu');
        }

        if (UserPower::checkUserPower('Order_100Fen_Deliver')) { //确认发货
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_deliver', 'text' => '确认发货', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Order_100Fen_Del')) { //取消订单
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_cancel', 'text' => '取消订单', 'icon' => 'fa-trash');
        }
        $proofState = Order::$fields['proofState'];
        $tabState = Order::$fields['tabState'];
        $tabState['']   = '订单状态';
        $proofState[''] = '审核状态';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_proofState', 'data' => $proofState, 'default' => '','style' => 'width:100px;' );
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_orderState', 'data' => $tabState , 'default' => '','style' => 'width:100px;' );
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Order_TabletList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 确认发货表单
     *
     * @param $no
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180509
     */
    public function deliverFormAction($no){
        $this->view->pick('order/deliverForm');
        Assets::datetimePicker();
        return $this->view->setVars([
            'no' => $no
        ]);
    }

    /**
     * 平板发货
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180509
     * modify by ck 20180524    添加发货时间判断，运单号中文判断
     * modify by ck 20180525    发单日期取消，改为获取当前日期
     */
    public function deliverTabletAction(){
        $postData = $this->request->getPost();
        try {
            $postData['deliverDate'] = date('Y-m-d H:i:s');
            if (mb_strlen($postData['trackingNo']) != mb_strlen($this->filter->sanitize($postData['trackingNo'], 'alphanum'))) {
                throw new \Exception('运单号不能包含除字母及数字外字符');
            }
            $postData['expressTarget'] = intval($postData['expressTarget']);
            $res = Order::deliverOrder($postData);
            if($res['code'] != 200) {
                return $this->sendErrorResponse($res['code'] , $res['msg'] );
            }
            $detail = Order::orderDetail(['orderNo' => $postData['orderNo']]);
            if($detail['code'] != 200) {
                return $this->sendErrorResponse($detail['code'] , $detail['msg'] );
            }
            $detail = $detail['data'];
            if ($postData['expressTarget'] == 1) {//个人
                $str = "亲爱的{$detail['buyerName']}家长，您于{$detail['createTime']} 提交的订单{$detail['no']}已经出库，由{$detail['deliverName']}为您配送，快递单号：{$postData['trackingNo']}，请您留意查收。您可以登录百分网\"我的订单\"查看订单物流信息";
                $phone = $detail['userMobile'];
            } else if ($postData['expressTarget'] == 2) { //学校
                $str = "亲爱的{$detail['buyerName']}家长，您于{$detail['createTime']} 提交的订单{$detail['no']}已经出库，将会统一发至校方，注意查收";
                $phone = $detail['userMobile'];
            } else { //未知类型
                return $this->sendErrorResponse(500 ,'未知类型');
            }
            $result = $this->sendSMS($phone , $str);
            if (!$result) {
                return $this->sendErrorResponse(500, '短信发送失败');
            }
            return $this->sendSuccessResponse('发货成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500 , $e->getMessage() );
        }

    }

    /**
     * 获取订单列表
     *
     * @param $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180509
     */
    public function getOrderListAction($type){
        $page = $this->request->getPost('page', 'int');
        $size = $this->request->getPost('rows', 'int');
        $proofState = $this->request->getPost('proofState', 'string');
        $orderState = $this->request->getPost('orderState', 'string');
        $key        = $this->request->getPost('key', 'string');
        $order      = $this->request->getPost('order', 'string');
        $sort       = $this->request->getPost('sort', 'string');
        try {
            if ( $type == 'course' ){
                $extraParams = [];
                if ( $proofState ){
                    $extraParams['proofStatus'] = $proofState;
                }
                if ( $orderState ) {
                    $extraParams['status'] = $orderState;
                }
                if ( $key ) {
                    $extraParams['keywords'] = $key;
                }
                if ($order && $sort) {
                    $extraParams['sortBy'] = $sort.'^'.$order;
                }else{
                    $extraParams['sortBy'] = 'createTime^desc';
                }
                $data = Order::getOrders($page , $size , $extraParams);
                Tool::runEnum($data['rows'],['status'=> Order::$fields['orderState'],'payProofStatus'=>Order::$fields['proofState']]);
            } else if ($type == 'tablet') {
                $extraParams = [];
                if ( $proofState ){
                    $extraParams['proofStatus'] = $proofState;
                }
                if ( $orderState ) {
                    $extraParams['status'] = $orderState;
                }
                if ( $key ) {
                    $extraParams['keywords'] = $key;
                }
                if ($order && $sort) {
                    $extraParams['sortBy'] = $sort.'^'.$order;
                }else{
                    $extraParams['sortBy'] = 'createTime^desc';
                }
                $data = Order::getTabOrders($page , $size , $extraParams);
                Tool::runEnum($data['rows'],['status'=> Order::$fields['tabState'] ,'payProofStatus'=>Order::$fields['proofState'] ]);
            } else {
                return $this->sendDataGridError('未知类型');
            }
            return $this->sendJsonResponse($data);
        } catch ( \Exception $e) {
            return $this->sendDataGridError($e->getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180517
     */
    public function cancelOrderAction(){
        try{
            $postData = $this->request->getPost();
            $res = Order::cancelOrderAction($postData);
            if ($res['code'] != 200 ) {
                return $this->sendErrorResponse($res['code'] , $res['msg'] );
            }
            return $this->sendSuccessResponse($res['msg']);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }


    /**
     * 通过订单
     *
     * create by xjq 20180509
     * modify by ck 20180524    添加短信发送
     */
    public function  passOrderAction(){
        $no    = $this->request->getPost('no', 'string');
        $payNo = $this->request->getPost('payProofTradeNo', 'string');
        try {
            $params = [
                'operatorDate' => date('Y-m-d H:i:s', time()),
                'operatorUser' => Main::getLoginUserInfo('userName'),
                'orderNo'      => $no,
                'payNo'        => $payNo
            ];
            $res = Order::passOrder($params);
            if ($res['code'] != 200 ) {
                return $this->sendErrorResponse($res['code'], $res['msg'] );
            }
            $detail = Order::orderDetail(['orderNo' => $no]);
            if ($detail['code'] != 200) {
                throw new \Exception('短信发送失败');
            }
            $detail = $detail['data'];
            $result = $this->sendSMS($detail['userMobile'], "亲爱的{$detail['buyerName']}家长，你的订单（单号：{$no}）线下转账审核成功。如有疑问，请联系辅导员。");
            if (!$result) {
                throw new \Exception('短信发送失败');
            }
            return $this->sendSuccessResponse($res['msg']);
        } catch ( \Exception $e) {
            return $this->sendErrorResponse(500 , $e->getMessage());
        }

    }

    /**
     * 拒绝表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180509
     */
    public function rejectFormAction($no){
        $this->view->pick('order/rejectForm');//拒绝表单
        return $this->view->setVars([
            'no' => $no,
        ]);
    }

    /**
     * 取消订单
     *
     * @param $no
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180517
     */
    public function cancelFormAction($no){
        $this->view->pick('order/cancelForm');//拒绝表单
        return $this->view->setVars([
            'no' => $no,
        ]);
    }


    /**
     * 拒绝订单
     *
     * create by xjq 20180509
     * modify by ck 20180524    添加短信通知
     */
    public function rejectOrderAction(){
        try {
            $no     = $this->request->getPost('no' , 'string');
            $reason = $this->request->getPost('reason' , 'string');
            $paramUrl = [
                'operatorDate' => date('Y-m-d H:i:s' , time()) ,
                'operatorUser' => Main::getLoginUserInfo('userName'),
                'orderNo'      => $no,
                'reason'       => $reason,
            ];
            $res = Order::rejectOrder($paramUrl);
            if ($res['code'] != 200) {
                return $this->sendErrorResponse($res['code'], $res['msg']);
            }
            $detail = Order::orderDetail(['orderNo' => $no]);
            if ($detail['code'] != 200) {
                throw new \Exception('短信发送失败');
            }
            $detail = $detail['data'];
            $result = $this->sendSMS($detail['userMobile'], "亲爱的{$detail['buyerName']}家长，你的订单（单号：{$no}）线下转账审核失败。如有疑问，请联系辅导员。");
            if (!$result) {
                throw new \Exception('短信发送失败');
            }
            return $this->sendSuccessResponse($res['msg']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 绑定学生列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by xjq 20180516
     * modify by ck 20180709
     */
    public function bindStudentAction(){
        try {
            $parentId = $this->request->getQuery('parentId');
            if(!$parentId){
                return $this->sendViewError('缺少参数');
            }
            $data = UserService::getAssociationByParent($parentId);
            if (count($data) <= 0 ) {
                return $this->sendViewError('没有绑定的学生');
            }
            $this->view->pick('order/bindStudent');
            Assets::importJs('js/order/bindStudent.js');
            return $this->view->setVars([
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 删除绑定
     *
     * create by xjq 20180516
     * modify by ck 20180709
     */
    public function cancelBindAction(){
        try {
            $studentId = $this->request->getPost('studentId', 'int');
            $parentId = $this->request->getPost('parentId', 'int');
            UserService::delAssociation($parentId, $studentId);
            $parent = XhsysUser::findFirst([
                'columns'    => 'sSelfPhone',
                'conditions' => 'iUserId = :iUserId:',
                'bind'       => ['iUserId' => $parentId],
            ])->toArray();
            $student = XhsysUser::findFirst([
                'columns'    => 'sSelfPhone',
                'conditions' => 'iUserId = :iUserId:',
                'bind'       => ['iUserId' => $studentId],
            ])->toArray();
            $res = $this->sendSMS($parent['sSelfPhone'], "亲爱的家长您好！我们已经解除您和{$student['sUserName']}学生的绑定关系，如有疑问，请联系辅导员");
            if (!$res) {
                return $this->sendErrorResponse(500, '短信发送失败');
            }
            return $this->sendSuccessResponse('解绑成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 拒绝退款表单
     *
     * @param $no
     *
     *  @return \Phalcon\Mvc\View
     *
     * create by xjq 20180509
     */
    public function refundRefuseAction($no){
        $this->view->pick('order/refundRefuse');
        return $this->view->setVars([
            'no' => $no,
        ]);
    }


    /**
     * 拒绝退款
     *
     * create by xjq 20180509
     */
    public function refuseRefundAction(){
        try {
            $no     = $this->request->getPost('no' , 'string');
            $reason = $this->request->getPost('reason' , 'string');
            $paramUrl = [
                'orderNo'  => $no,
                'reason'   => $reason,
            ];
            $res = Order::refundRefuse($paramUrl);
            if($res['code'] != 200) {
                return $this->sendErrorResponse($res['code'] , $res['msg']);
            }
            return $this->sendSuccessResponse($res['msg']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 申请退款表单
     *
     * @param $no
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180606
     */
    public function refundAgreeAction($no){
        $this->view->pick('order/refundAgree');
        return $this->view->setVars([
            'no' => $no,
        ]);
    }

    /**
     * 同意退款
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180606
     */
    public function agreeRefundAction(){
        $no      = $this->request->getPost('no', 'string');
        $reason  = $this->request->getPost('reason', 'string');
        $amount  = $this->request->getPost('amount', 'string');
        try {
            $paramUrl = [
                'orderNo'  => $no,
                'reason'   => $reason,
                'amount'   => $amount,
            ];
            $res = Order::refundRefuse($paramUrl);
            if ($res['code'] != 200) {
                return $this->sendErrorResponse($res['code'], $res['msg']);
            }
            return $this->sendSuccessResponse($res['msg']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }




    /**
     * 发送短信息
     *
     * @param $sTel
     * @param $sMessage
     * @param string $channelId
     * @return bool
     *
     * create by xjq 20180516
     */
    public  function sendSMS($sTel, $sMessage , $channelId='')
    {
        $channelId or $channelId = 'SMS_SHIYUAN2';
        $http = new HttpClient();
        $http->setBaseUrl(Main::getConfigByName('resServerInterface')['sendMsgServiceUrl'].'/api/v1/messages');
        $result = $http->postJson(null , array(
            "type"      => "SMS",
            "payload"   => $sMessage,
            "clientId"  => $sTel,
            "appId"     => 'CA102002',
            "channelId" => $channelId,
        ) );
        return $result->isSuccess();
    }
}